<template>
  <div class="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-50">
    <div class="container mx-auto px-4 py-8">
      <!-- 页面标题 -->
      <div class="mb-8 text-center">
        <div class="inline-flex items-center justify-center w-16 h-16 bg-gradient-to-r from-green-600 to-blue-600 rounded-2xl mb-4 shadow-lg">
          <svg class="w-8 h-8 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
          </svg>
        </div>
        <h1 class="text-4xl font-bold bg-gradient-to-r from-gray-900 to-gray-700 bg-clip-text text-transparent mb-2">创建项目</h1>
        <p class="text-gray-600 text-lg">分享你的创意作品，让更多人看到</p>
      </div>

      <!-- 创建表单 -->
      <div class="max-w-4xl mx-auto">
        <div class="bg-white/80 backdrop-blur-sm rounded-2xl shadow-lg border border-white/20 p-8">
          <form @submit.prevent="submitProject">
            <!-- 基本信息 -->
            <div class="mb-8">
              <h2 class="text-2xl font-bold text-gray-900 mb-6">基本信息</h2>
              
              <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <!-- 项目标题 -->
                <div class="md:col-span-2">
                  <label for="title" class="block text-sm font-medium text-gray-700 mb-2">
                    项目标题 <span class="text-red-500">*</span>
                  </label>
                  <input
                    id="title"
                    v-model="form.title"
                    type="text"
                    required
                    placeholder="请输入项目标题"
                    class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"
                  >
                </div>

                <!-- 项目类型 -->
                <div>
                  <label for="type" class="block text-sm font-medium text-gray-700 mb-2">
                    项目类型 <span class="text-red-500">*</span>
                  </label>
                  <select
                    id="type"
                    v-model="form.type"
                    required
                    class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"
                  >
                    <option value="">请选择项目类型</option>
                    <option value="web">Web应用</option>
                    <option value="mobile">移动应用</option>
                    <option value="desktop">桌面应用</option>
                    <option value="library">开源库</option>
                    <option value="tool">开发工具</option>
                    <option value="other">其他</option>
                  </select>
                </div>

                <!-- 难度等级 -->
                <div>
                  <label for="difficulty" class="block text-sm font-medium text-gray-700 mb-2">
                    难度等级 <span class="text-red-500">*</span>
                  </label>
                  <select
                    id="difficulty"
                    v-model="form.difficulty"
                    required
                    class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"
                  >
                    <option value="">请选择难度等级</option>
                    <option value="beginner">入门</option>
                    <option value="intermediate">中级</option>
                    <option value="advanced">高级</option>
                  </select>
                </div>

                <!-- 项目描述 -->
                <div class="md:col-span-2">
                  <label for="description" class="block text-sm font-medium text-gray-700 mb-2">
                    项目描述 <span class="text-red-500">*</span>
                  </label>
                  <textarea
                    id="description"
                    v-model="form.description"
                    required
                    rows="3"
                    placeholder="请简要描述你的项目"
                    class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200 resize-none"
                  ></textarea>
                </div>
              </div>
            </div>

            <!-- 技术栈 -->
            <div class="mb-8">
              <h2 class="text-2xl font-bold text-gray-900 mb-6">技术栈</h2>
              
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">
                  使用的技术 <span class="text-red-500">*</span>
                </label>
                <div class="flex flex-wrap gap-2 mb-4">
                  <span
                    v-for="(tech, index) in form.tech_stack"
                    :key="index"
                    class="inline-flex items-center px-3 py-1 bg-blue-100 text-blue-800 rounded-full text-sm"
                  >
                    {{ tech }}
                    <button
                      type="button"
                      @click="removeTech(index)"
                      class="ml-2 text-blue-600 hover:text-blue-800"
                    >
                      <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                      </svg>
                    </button>
                  </span>
                </div>
                <div class="flex gap-2">
                  <input
                    v-model="newTech"
                    type="text"
                    placeholder="输入技术名称"
                    class="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                    @keyup.enter="addTech"
                  >
                  <button
                    type="button"
                    @click="addTech"
                    class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors"
                  >
                    添加
                  </button>
                </div>
              </div>
            </div>

            <!-- 项目内容 -->
            <div class="mb-8">
              <h2 class="text-2xl font-bold text-gray-900 mb-6">项目详情</h2>
              
              <div>
                <label for="content" class="block text-sm font-medium text-gray-700 mb-2">
                  详细内容 <span class="text-red-500">*</span>
                </label>
                <textarea
                  id="content"
                  v-model="form.content"
                  required
                  rows="10"
                  placeholder="请详细介绍你的项目，包括功能特性、技术实现、使用说明等"
                  class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200 resize-none"
                ></textarea>
                <p class="text-sm text-gray-500 mt-2">支持 Markdown 格式</p>
              </div>
            </div>

            <!-- 项目链接 -->
            <div class="mb-8">
              <h2 class="text-2xl font-bold text-gray-900 mb-6">项目链接</h2>
              
              <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label for="github_url" class="block text-sm font-medium text-gray-700 mb-2">
                    GitHub 仓库
                  </label>
                  <input
                    id="github_url"
                    v-model="form.github_url"
                    type="url"
                    placeholder="https://github.com/username/repository"
                    class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"
                  >
                </div>

                <div>
                  <label for="demo_url" class="block text-sm font-medium text-gray-700 mb-2">
                    在线演示
                  </label>
                  <input
                    id="demo_url"
                    v-model="form.demo_url"
                    type="url"
                    placeholder="https://your-demo.com"
                    class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"
                  >
                </div>
              </div>
            </div>

            <!-- 项目图片 -->
            <div class="mb-8">
              <h2 class="text-2xl font-bold text-gray-900 mb-6">项目图片</h2>
              
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">
                  封面图片
                </label>
                <div class="flex items-center space-x-4">
                  <div v-if="form.cover_image" class="w-32 h-32 rounded-lg overflow-hidden border border-gray-300">
                    <img :src="form.cover_image" alt="封面图片" class="w-full h-full object-cover">
                  </div>
                  <div>
                    <input
                      ref="coverImageInput"
                      type="file"
                      accept="image/*"
                      @change="handleCoverImageUpload"
                      class="hidden"
                    >
                    <button
                      type="button"
                      @click="coverImageInput?.click()"
                      class="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
                    >
                      选择图片
                    </button>
                    <p class="text-sm text-gray-500 mt-1">建议尺寸: 800x600px</p>
                  </div>
                </div>
              </div>

              <div class="mt-6">
                <label class="block text-sm font-medium text-gray-700 mb-2">
                  项目截图
                </label>
                <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
                  <div
                    v-for="(image, index) in form.images"
                    :key="index"
                    class="relative w-full h-32 rounded-lg overflow-hidden border border-gray-300"
                  >
                    <img :src="image" alt="项目截图" class="w-full h-full object-cover">
                    <button
                      type="button"
                      @click="removeImage(index)"
                      class="absolute top-2 right-2 w-6 h-6 bg-red-500 text-white rounded-full flex items-center justify-center hover:bg-red-600 transition-colors"
                    >
                      <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                      </svg>
                    </button>
                  </div>
                  <div
                    v-if="form.images.length < 8"
                    @click="imagesInput?.click()"
                    class="w-full h-32 border-2 border-dashed border-gray-300 rounded-lg flex items-center justify-center cursor-pointer hover:border-gray-400 transition-colors"
                  >
                    <div class="text-center">
                      <svg class="w-8 h-8 text-gray-400 mx-auto mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
                      </svg>
                      <p class="text-sm text-gray-500">添加图片</p>
                    </div>
                  </div>
                </div>
                <input
                  ref="imagesInput"
                  type="file"
                  accept="image/*"
                  multiple
                  @change="handleImagesUpload"
                  class="hidden"
                >
                <p class="text-sm text-gray-500 mt-2">最多上传8张图片，每张图片不超过5MB</p>
              </div>
            </div>

            <!-- 提交按钮 -->
            <div class="flex justify-end space-x-4">
              <button
                type="button"
                @click="router.back()"
                class="px-6 py-3 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
              >
                取消
              </button>
              <button
                type="submit"
                :disabled="submitting"
                class="px-6 py-3 bg-blue-500 text-white rounded-lg hover:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                <span v-if="submitting" class="flex items-center">
                  <svg class="animate-spin -ml-1 mr-3 h-5 w-5 text-white" fill="none" viewBox="0 0 24 24">
                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                    <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                  </svg>
                  发布中...
                </span>
                <span v-else>发布项目</span>
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { projectApi } from '@/api/project'

const router = useRouter()

// 表单数据
const form = ref({
  title: '',
  description: '',
  content: '',
  type: '',
  difficulty: '',
  tech_stack: [] as string[],
  github_url: '',
  demo_url: '',
  cover_image: '',
  images: [] as string[]
})

// 其他状态
const newTech = ref('')
const submitting = ref(false)
const coverImageInput = ref<HTMLInputElement>()
const imagesInput = ref<HTMLInputElement>()

// 方法
const addTech = () => {
  const tech = newTech.value.trim()
  if (tech && !form.value.tech_stack.includes(tech)) {
    form.value.tech_stack.push(tech)
    newTech.value = ''
  }
}

const removeTech = (index: number) => {
  form.value.tech_stack.splice(index, 1)
}

const handleCoverImageUpload = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  if (!file) {
    // 重置input的value，确保下次选择文件时change事件能正常触发
    target.value = ''
    return
  }

  try {
    const response = await projectApi.uploadProjectImage(file)
    if (response.data) {
      form.value.cover_image = response.data.url
    }
  } catch (err) {
    console.error('上传封面图片失败:', err)
    alert('上传封面图片失败，请重试')
  } finally {
    // 重置input的value，确保下次选择文件时change事件能正常触发
    target.value = ''
  }
}

const handleImagesUpload = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const files = target.files
  if (!files) {
    // 重置input的value，确保下次选择文件时change事件能正常触发
    target.value = ''
    return
  }

  for (const file of Array.from(files)) {
    if (form.value.images.length >= 8) break
    
    try {
      const response = await projectApi.uploadProjectImage(file)
      if (response.data) {
        form.value.images.push(response.data.url)
      }
    } catch (err) {
      console.error('上传图片失败:', err)
    }
  }
  
  // 重置input的value，确保下次选择文件时change事件能正常触发
  target.value = ''
}

const removeImage = (index: number) => {
  form.value.images.splice(index, 1)
}

const submitProject = async () => {
  if (form.value.tech_stack.length === 0) {
    alert('请至少添加一个技术栈')
    return
  }

  submitting.value = true
  
  try {
    const response = await projectApi.createProject({
      title: form.value.title,
      description: form.value.description,
      content: form.value.content,
      type: form.value.type,
      difficulty: form.value.difficulty,
      tech_stack: form.value.tech_stack,
      github_url: form.value.github_url,
      demo_url: form.value.demo_url,
      cover_image: form.value.cover_image,
      images: form.value.images
    })

    if (response.data) {
      alert('项目创建成功！')
      router.push(`/projects/${response.data.id}`)
    }
  } catch (err) {
    console.error('创建项目失败:', err)
    alert('创建项目失败，请重试')
  } finally {
    submitting.value = false
  }
}
</script>
